#include "libsys.h"
#if !defined(WIN32)
#include <signal.h>
#include <unistd.h>
#include <sys/time.h>
#else
#include <io.h>

#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <cstdlib>

using namespace std;
using namespace basic::library2;


bool CSys::m_bShouldStop = true;

CSys::CSys(void)
{
}

CSys::~CSys(void)
{
}

void sys_sig_handle(int signo)
{
	CSys::m_bShouldStop = true;
}

void CSys::InitDaemon()
{
#if !defined(WIN32)
	pid_t pid;
    apr_int32_t i;

	pid = fork();
	if (pid > 0)
		exit(0);
	else if (pid < 0)
	{
		perror("fail to fork.");
		exit(1);
	}

   /* now the process is the leader of the session, the leader of its
      process grp, and have no controlling tty */
  	if(setsid() == - 1)
  	{
		perror("omail: setsid() fail. It seems impossible.");
		exit(1);
	}
   	setpgid(0, 0);

	/*** change umask */
	umask(0027);

	/* ignore the SIGHUP, in case the session leader sending it when terminating.  */
	signal(SIGHUP, SIG_IGN);
	signal(SIGINT, SIG_IGN);
	signal(SIGQUIT, SIG_IGN);
	signal(SIGPIPE, SIG_IGN);
	signal(SIGURG, SIG_IGN);
	signal(SIGTSTP, SIG_IGN);
	signal(SIGTTIN, SIG_IGN);
	signal(SIGTTOU, SIG_IGN);
	signal(SIGALRM, SIG_IGN);
	signal(SIGCHLD, SIG_IGN);
    signal(SIGTERM, sys_sig_handle);

	pid = fork();
	if (pid > 0)
		exit(0);
	else if (pid < 0)
	{
		perror("fail to fork.");
		exit(1);
	}
	/*** close all inherited file/socket descriptors */
	for(i = 3; i < getdtablesize(); i ++)
		close(i);
	close(0);

	m_bShouldStop = false;
#endif
}

apr_int32_t CSys::UMask(apr_int32_t dwMask)
{
#if defined(WIN32)
    return _umask(dwMask);
#else
    return umask(dwMask);
#endif
}

apr_int32_t CSys::Fork()
{
#if defined(WIN32)
    return -1;
#else
    return (apr_int32_t)fork();
#endif
}
